// const pool = require("../../config/db");
var multiparty = require("multiparty");
var fs = require("fs");
var xlsx = require("node-xlsx");
module.exports.install = function (express) {
  const file_obj = express.Router();
  file_obj.post("/execl", function (req, res) {
    console.log(req, "req");
    const userInfo = req.headers.userInfo;
    let url = "E:/node_vue_admin/server/public";
    let form = new multiparty.Form({
      uploadDir: url, //指定上传的文件路径
    });
    form.parse(req, (err, field, files) => {
      console.log(files, field, err);
      let names;
      files &&
        files.file.map((x) => {
          names = url + "/" + x.originalFilename;
          // 必须这样写
          fs.renameSync(x.path, names);
        });
      var obj = xlsx.parse(names);

      res.json({
        userInfo: userInfo,
        data: obj,
      });
    });
    form.on("field", (name, value) => {
      // name:字段名
      // value:值
      console.log("数据:", name, value);
    });
    //接收文件数据
    form.on("file", (name, file) => {
      console.log("文件:", name, file);
    });
    //表单解析完成
    form.on("close", () => {
      console.log("完成");
    });
  });
  file_obj.get("/init", function (req, res) {
    const data = [
      ["q", "w", "e"],
      [1, 2, 3],
      ["dd", "dd", "ddd"],
    ];
    //配置，设置列宽
    const options = { "!cols": [{ wch: 6 }, { wch: 7 }, { wch: 10 }] };
    //生成二进制数据流
    var buffer = xlsx.build([{ name: "mySheetName", data: data }], options);
    //写入文件
    fs.writeFileSync("E:/node_vue_admin/server/public/data.xlsx", buffer, {
      flag: "w",
    });
    res.json({
      code: 0,
      data: "http://localhost:3000/public/data.xlsx",
      message: "成功",
    });
    // fs.appendFile(
    //   "E:/node_vue_admin/server/public/data.xlsx",
    //   buffer,
    //   function (err) {
    //     if (err) {
    //       console.log(err, "保存excel出错");
    //     } else {
    //       console.log("写入excel成功!!!");

    //     }
    //   }
    // );
  });
  return file_obj;
};
